package com.anthonybennis.blender.client.pages.tipofday;

import java.util.HashMap;
import java.util.Map;

import com.anthonybennis.blender.client.DatabaseReader;
import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.TextResource;
import com.google.gwt.user.client.Random;

/**
 * 
 * @author abennis
 */
public class TipsFactory 
{
	
	private final int NUMBER_OF_TIPS = 25;
	private final int MINIMUM_NUMBER_OF_TIPS = 1;
	private final Map<Integer, TipData> _tipData = TipsFactory.loadTipsDB();
	
	
	/**
	 * 
	 */
	public TipData createRandomTip()
	{
		TipData tipData = null;
		
		/*
		 * Get a new tip randomily
		 */
		int randomTipID = this.randomInt();
		tipData = this.createTipData(randomTipID);
		
		return tipData;
	}
	
	private int randomInt() 
	{
	    // nextInt is normally exclusive of the top value,
	    // so add 1 to make it inclusive
	    int randomNum = Random.nextInt((NUMBER_OF_TIPS - MINIMUM_NUMBER_OF_TIPS) + 1) + MINIMUM_NUMBER_OF_TIPS;

	    return randomNum;
	}
	
	/**
	 * 
	 * @param tipID
	 * @return
	 */
	private TipData createTipData(int tipID)
	{
		TipData tipData = _tipData.get(tipID);
		return tipData;
	}
	
	/**
	 * 
	 */
	private static Map<Integer, TipData> loadTipsDB()
	{
		Map<Integer, TipData> tipDataMap = new HashMap<Integer, TipData>();
		
		TipsDBClientBundle tipsClientBundle = (TipsDBClientBundle)GWT.create(TipsDBClientBundle.class);
		TextResource textResource = tipsClientBundle.tipsDB();
		String allText = textResource.getText();
		allText = allText.replaceAll("(\\r|\\n)", "");
		String[] tipDataAsArray = allText.split(DatabaseReader.TERMINATION_CHARACTER);
		
		for (String unprocessedTipData : tipDataAsArray) 
		{
			TipData data = createTipData(unprocessedTipData);
			tipDataMap.put(data.getID(), data);
		}
		
		return tipDataMap;
	}
	
	/**
	 * 
	 * @param commaSeperaterdData
	 * @return
	 */
	private static TipData createTipData(String commaSeperaterdData)
	{
		String[] tipDataAsArray = commaSeperaterdData.split(DatabaseReader.SEPERATOR);

		String idAsString = tipDataAsArray[0];
		idAsString = idAsString.trim();
		int id = Integer.parseInt(idAsString);
		String title = tipDataAsArray[1];
		String description = tipDataAsArray[2]; // TODO AB Consider supporting HTML in description for nicer formated text.
		String imageURL = "Tip" + idAsString + ".png"; // Dynamically generate Image file name.
		String blenderVersion = tipDataAsArray[3];
		
		return new TipData(id, title, imageURL, description, blenderVersion);
	}
}